<script setup lang="ts">
import { RouterLink, RouterView } from 'vue-router'
import { YkMenu, YkContent, YkTaskBar, utils } from 'yklib'
import router from './router'
import { computed, onMounted, ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useToolStore } from './stores/tool'

const {
  isLogin,
  currentUsername,
  currentUserEmail,
  vip,
  money,
  lastLogin,
  lastTickTime,
  accountStatus,
  processing
} = storeToRefs(useToolStore())

const quit = () => {
  console.log('退出')
  window.pywebview.api.quit().then((response: string) => {
    alert(response)
  })
}

onMounted(() => {
  router.push('/login')
})

const content = ref<InstanceType<typeof YkContent>>()

const options = [
  {
    label: '文件',
    submenu: [
      {
        label: '下载',
        click: () => {
          // isLogin.value = false
          // currentUsername.value = '未登录'
          // vip.value = 0
          // money.value = 0
          // lastTickTime.value = ''
          router.push('/download')
        }
      }, {
        label: '退出',
        click: () => {
          // isLogin.value = false
          // currentUsername.value = '未登录'
          // vip.value = 0
          // money.value = 0
          // lastTickTime.value = ''
          // router.push('/login')
          quit()
        }
      },
      // {
      //   label: '保存',
      //   click: () => {
      //     router.push('/about')
      //   }
      // },
      {
        label: '运行',
        click: () => {
          router.push('/download')
        }
      },
      {
        label: '打开终端',
        click: () => {
          if (content.value) {
            content.value.openDrawer()
          }
        }
      }
    ]
  },
  {
    label: '设置',
    submenu: [
      {
        label: '设置',
        click: () => {
          router.push('/settings')
        }
      }
    ]
  },
  {
    label: '存储',
    submenu: [
      // {
      //   label: '本地存储路径设置',
      //   click: () => {
      //     router.push('/login')
      //   }
      // },
      // {
      //   label: 'MySQL存储设置',
      //   click: () => {
      //     router.push('/about')
      //   }
      // },
      {
        label: '清空存储数据',
        click: () => {
          router.push('/download')
        }
      },
      {
        label: '查询定时任务',
        click: () => {
          if (processing.value) {
            alert('有一次性任务正在进行，请稍后再试！')
            return
          }
          window.pywebview.api.getJobs()
        }
      },
      {
        label: '帮助',
        click: () => {
          window.open('https://gitee.com/yangke02/stocks')
          // router.push('/help')
        }
      }
    ]
  }
]

const user = computed(() => {
  return {
    username: currentUsername.value,
    email: currentUserEmail.value,
    money: money.value,
    vip: vip.value,
    lastLogin: lastLogin.value,
    isLogin: isLogin.value
  }
})


const handleEvent = (buttonId: 'button1' | 'button2') => {
  if (buttonId === 'button1') { // 充值
    utils._chargeCoin(currentUsername.value)
  } else if (buttonId === 'button2') {
    currentUsername.value = '' as any
    currentUserEmail.value = '' as any
    currentUserEmail.value = 0 as any
    currentUserEmail.value = 0 as any
    lastLogin.value = '' as any
    isLogin.value = false as any
    router.push('./login') // 返回登录页面
  }
}

const display = computed(() => {// 当是登录页面时，菜单和任务栏不显示，否则显示
  if (router.currentRoute.value.name === 'login') {
    return false
  } else {
    return true
  }
})

const menuHeight = computed(() => {
  if (router.currentRoute.value.name === 'login') {
    return 0
  } else {
    return 24
  }
})

const taskBarHeight = computed(() => {
  if (router.currentRoute.value.name === 'login') {
    return 0
  } else {
    return 24
  }
})

let connErrTries = 0
const sendLoginMessage = async () => {
  if (currentUsername.value === '未登录') {
    connErrTries = 0
    return
  }
  const today = new Date()
  const today_str = `${today.getFullYear()}${today.getMonth() + 1}${today.getDate()}`
  if (lastTickTime.value.slice(0, 8) === today_str) { // 如果当天已经systemTick过了，则不在发送心跳
    console.log('already ticked')
  } else {
    const res = await utils.systemTick('https://sges.yangke.site:5001', currentUsername.value)
    if (res.Status === 'Connection Error' || res.Status === 'Server Error') {
      connErrTries += 1
      if (connErrTries >= 10) {
        isLogin.value = false // 服务器连接失败
      }
    } else if (res.Status === 'success' || res.Status === 'arrear') {
      money.value = res.Money
      connErrTries = 0
      lastTickTime.value = today_str
    }
  }
}

const taskBarContent = ref('')
const taskProgress = ref(0)
const displayProgress = computed(() => {
  if (taskProgress.value <= 0.01 || taskProgress.value >= 99.99) {
    return false
  } else {
    return true
  }
})

const setTaskBar = (text: string, progress: number) => {
  taskBarContent.value = text
  taskProgress.value = progress
}


onMounted(() => {
  window.setTaskBarContent = setTaskBar // throttle(appendText, 100)
})
const intervalId = setInterval(sendLoginMessage, 60000)
</script>

<template>
  <div>
    <YkMenu v-if="display" :options="options" :height="menuHeight" @card-event="handleEvent"
            :user="user" button1-text="充值"></YkMenu>
    <YkContent ref="content" class="bg-green-100" :menu-bar-height="menuHeight" :task-bar-height="taskBarHeight">
      <RouterView />
    </YkContent>
    <YkTaskBar v-if="display" class="bg-red-100" :height="taskBarHeight">
      <div class="w-full grid grid-cols-4 pl-2">
        <div class="col-span-3">
          <span> {{ taskBarContent }} </span>
        </div>
        <div class="col-span-1">
          <meter class="w-full" min="0" max="100" :value="taskProgress" v-if="displayProgress">{{ taskBarContent }}
          </meter>
        </div>
      </div>
    </YkTaskBar>
  </div>
</template>

<style>
@import "tailwindcss";
@import "yklib/dist/style.css";


</style>
